package com.donghua.controller;

import com.donghua.entity.User;
import com.donghua.enums.StatusCodeEnum;
import com.donghua.service.LoginService;
import com.donghua.service.UserService;
import com.donghua.util.HostHolder;
import com.donghua.util.Result;
import com.donghua.vo.UserVO;
import com.donghua.util.CommunityConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import static com.donghua.enums.StatusCodeEnum.*;

@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @GetMapping("users/code")
    @ResponseBody
    public Result<?> sendCode(String username, String nickName) {
        if(nickName == null) {
            return Result.ok(USER_NICKNAME_ERROR.getCode(), USER_NICKNAME_ERROR.getMsg());
        }
        User user = userService.findUserByNickName(nickName);
        if(user != null) {
            return Result.ok(NICKNAME_EXIST.getCode(), NICKNAME_EXIST.getMsg());
        }
        loginService.sendCode(username);
        logger.info("验证码已发送成功");
        return Result.ok(StatusCodeEnum.SUCCESS.getCode(), StatusCodeEnum.SUCCESS.getMsg());
    }

    @PostMapping("/register")
    @ResponseBody
    public Result<?> register(UserVO user) {
        loginService.register(user);
        logger.info("用户注册成功");
        return Result.ok(StatusCodeEnum.SUCCESS.getCode(), StatusCodeEnum.SUCCESS.getMsg());
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> login(String username, String password, HttpServletResponse response) {

        // 检查账号,密码
        int expiredSeconds = DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = loginService.login(username, password, expiredSeconds);

        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            logger.info("用户登录成功");
            User user = userService.findUserByName(username);
            hostHolder.setUser(user);
            return Result.ok(StatusCodeEnum.SUCCESS.getCode(), StatusCodeEnum.SUCCESS.getMsg());
        } else {
            String data;
            if (map.containsKey("usernameMsg")) {
                data = (String) map.get("usernameMsg");
                logger.info("用户名不存在");
                return Result.ok(USERNAME_NOT_EXIST.getCode(), USERNAME_NOT_EXIST.getMsg(), data);
            } else if (map.containsKey("passwordMsg")) {
                data = (String) map.get("passwordMsg");
                logger.info("用户密码错误");
                return Result.ok(PASSWORD_ERROR.getCode(), PASSWORD_ERROR.getMsg(), data);
            }
            logger.info("登录失败");
            return Result.ok(FAIL.getCode(), FAIL.getMsg());
        }
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> logout(@CookieValue("ticket") String ticket) {
        loginService.logout(ticket);
        logger.info("用户退出成功");
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg());
    }
}
